{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "toc": true
   },
   "source": [
    "<h1>目录<span class=\"tocSkip\"></span></h1>\n",
    "<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#需求\" data-toc-modified-id=\"需求-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>需求</a></span></li><li><span><a href=\"#思想\" data-toc-modified-id=\"思想-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>思想</a></span></li><li><span><a href=\"#实现\" data-toc-modified-id=\"实现-3\"><span class=\"toc-item-num\">3&nbsp;&nbsp;</span>实现</a></span></li></ul></div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 需求\n",
    "```\n",
    "将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 \n",
    "\n",
    "示例：\n",
    "\n",
    "输入：1->2->4, 1->3->4\n",
    "输出：1->1->2->3->4->4\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 思想\n",
    "1. 新建一个链表保存合并结果，dummy\n",
    "1. 在一个while循环中判断两个节点当前的节点的大小，添加值小的一个节点到dummy\n",
    "1. 处理长的一个链表的末尾部分的节点"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 实现"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def mergeTwoLists(self, l1, l2):\n",
    "    \"\"\"\n",
    "    :type l1: ListNode\n",
    "    :type l2: ListNode\n",
    "    :rtype: ListNode\n",
    "    \"\"\"\n",
    "    head = dummy = ListNode(-1)\n",
    "    while l1 and l2:\n",
    "        if l1.val < l2.val:\n",
    "            head.next = l1\n",
    "            l1 = l1.next\n",
    "        else:\n",
    "            head.next = l2\n",
    "            l2 = l2.next\n",
    "        head = head.next\n",
    "    if l1:\n",
    "        head.next = l1\n",
    "    if l2:\n",
    "        head.next = l2\n",
    "    return dummy.next\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "base"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "目录",
   "title_sidebar": "大纲",
   "toc_cell": true,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
